﻿namespace MyCompany.Core {
	using System;
	using System.Collections.Generic;
	using System.Windows.Input;

	/// <summary>
	///     NOTE: This code started from Dennis's code here:
	///     http://stackoverflow.com/questions/307004/changing-the-cursor-in-wpf-sometimes-works-sometimes-doesnt
	///     Usage:
	///     using (WaitStateIndicator cursor = new WaitStateIndicator()) { /*Do work*/ }
	/// </summary>
	public class WaitStateIndicator : IDisposable {
		static readonly Stack<Cursor> stack = new Stack<Cursor>();

		public WaitStateIndicator( /*Cursor newCursor*/) {
			var newCursor = Cursors.Wait;
			stack.Push(newCursor);

			// To avoid flickering, don't do the assignment unless required.
			// ReSharper disable once RedundantCheckBeforeAssignment
			if (Mouse.OverrideCursor != newCursor)
				Mouse.OverrideCursor = newCursor;
		}

		public void Dispose() {
			stack.Pop();

			var cursor = stack.Count > 0 ? stack.Peek() : null;

			// To avoid flickering, don't do the assignment unless required.
			// ReSharper disable once RedundantCheckBeforeAssignment
			if (cursor != Mouse.OverrideCursor)
				Mouse.OverrideCursor = cursor;
		}
	}
}
